package com.vitabuybuy.tv.ui.mine.address

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.ext.setOnclickNoRepeat
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityEditAddressBinding
import com.vitabuybuy.tv.dto.AddressListDto
import com.vitabuybuy.tv.dto.RegionDto
import com.library.common.toast.XToast
import com.vitabuybuy.tv.ui.mine.address.viewmodel.AddressViewModel
import com.vitabuybuy.tv.widget.selector.BottomDialog
import com.vitabuybuy.tv.widget.selector.SelectedListener
import kotlinx.android.synthetic.main.activity_edit_address.*


class EditAddressActivity : BaseActivity<AddressViewModel, ActivityEditAddressBinding>() {

    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_edit_address

    private lateinit var addressDetails: AddressListDto
    private var regionId = -1
    private var countryId = -1
    private var areaDialog: BottomDialog? = null


    override fun onGetBundle(bundle: Bundle?) {
        if (bundle?.getSerializable("addressDetails") != null) {
            btnDelete.visibility = View.VISIBLE
            addressDetails = bundle.getSerializable("addressDetails") as AddressListDto
        } else {
            btnDelete.visibility = View.INVISIBLE
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.isDefault = false
        setTitle(getString(R.string.add_new_address))
    }

    override fun observeData() {
        if (::addressDetails.isInitialized && addressDetails != null) {
            setTitle(getString(R.string.edit_address))
            etName.setText(addressDetails.name)
            etContactNumber.setText(addressDetails.phone)
            var regionStr = "";
            for ((index, region) in addressDetails.regionList.withIndex()) {
                if (index == 0) {
                    countryId = region.id
                    tvCountry.text = region.name
                } else {
                    regionStr += region.name
                    regionId = region.id
                }
            }
            tvArea.text = regionStr
            etDetailAddress.setText(addressDetails.detail)
            etPostalCode.setText(addressDetails.zipcode)
            mBinding.isDefault = addressDetails.isDefaulted
        }
    }

    override fun eventHandling() {
        setOnclickNoRepeat(rlCountry, rlArea, ivSetDefaultAddress, btnSave, btnDelete) { v ->
            when (v) {
                rlCountry -> {
                    areaDialog = BottomDialog(this, 1)
                    viewModel.getRegionList(null)
                }
                rlArea -> {
                    //这里一定要重新创建
                    areaDialog = BottomDialog(this, 5)
                    viewModel.getRegionList(countryId)
                }
                ivSetDefaultAddress -> {
                    mBinding.isDefault = !mBinding.isDefault!!
                }
                btnSave -> {
                    when {
                        etName.text.isEmpty() -> XToast.normal(getString(R.string.please_input_receiver_name))
                        etContactNumber.text.isEmpty() -> XToast.normal(getString(R.string.please_input_receiver_phone))
                        regionId == -1 -> XToast.normal(getString(R.string.area_tip))
                        etDetailAddress.text.isEmpty() -> XToast.normal(getString(R.string.pleaser_input_detail_by_area))
                        etPostalCode.text.isEmpty() -> XToast.normal(getString(R.string.input_postal_code))
                        else -> {
                            //修改收货地址
                            if (::addressDetails.isInitialized && addressDetails != null) {
                                viewModel.saveOrupdateAddress(
                                    etName.text.toString(),
                                    etContactNumber.text.toString(),
                                    regionId,
                                    etDetailAddress.text.toString(),
                                    etPostalCode.text.toString(),
                                    mBinding?.isDefault,
                                    addressDetails.id
                                )
                            } else {//保存收货地址
                                viewModel.saveOrupdateAddress(
                                    etName.text.toString(),
                                    etContactNumber.text.toString(),
                                    regionId,
                                    etDetailAddress.text.toString(),
                                    etPostalCode.text.toString(),
                                    mBinding.isDefault, -1
                                )
                            }
                        }
                    }
                }
                btnDelete -> {
                    AlertDialog.Builder(mContext)
                        .setTitle(getString(R.string.logout))
                        .setMessage(getString(R.string.are_you_sure_delete_address))
                        .setCancelable(true)
                        .setPositiveButton(getString(R.string.confirm)) { _, _ ->
                            viewModel.deleteAddress(addressDetails.id)
                        }
                        .setNegativeButton(getString(R.string.cancel)) { _, _ -> }.create()
                        .show()
                }
            }
        }
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            0 -> {
                viewModel.getDataList()
            }
            1 -> {
                areaDialog?.run {
                    this.setDataRegion(msg.obj as MutableList<RegionDto>)
                    this.setOnAddressSelectedListener(object : SelectedListener {
                        override fun onAddressSelected(selectAbles: ArrayList<RegionDto>?) {
                            selectAbles?.run {
//                                if (this.size == 1) {//表明只有国家可选
//                                    regionId = this[0].id
//                                    mBinding.tvArea.text = this[0].name
//                                    mBinding.tvCountry.text = this[0].name
//                                } else {//表明有国家和下属地区
                                    var area = ""
                                    for (selectAble in this) {
                                        area += selectAble.name
                                        regionId = selectAble.id
                                    }
                                    mBinding.tvArea.text = area
                                    areaDialog = null
//                                }
                            }
                        }

                        override fun onClickOnEach(selectAble: RegionDto?) {
                            viewModel.getRegionList(selectAble?.id)
                        }
                    })
                    if (this.isShowing) return
                    this.show()
                }
            }
            2 -> {
                XToast.success(
                    if (msg.arg1 == -1) getString(R.string.update_success) else getString(
                        R.string.save_success
                    )
                )
                finishResult(null)
            }
            3 -> {
                areaDialog?.run {
                    this.setDataRegion(msg.obj as MutableList<RegionDto>)
                    this.setOnAddressSelectedListener(object : SelectedListener {
                        override fun onAddressSelected(selectAbles: java.util.ArrayList<RegionDto>?) {
                            selectAbles?.run {
                                if(this[0].id == countryId){
                                    return@run
                                }
                                mBinding.tvCountry.text = this[0].name
                                countryId = this[0].id
                                //地区重新置空
                                regionId = -1
                                mBinding.tvArea.text = ""
                            }
                        }
                        override fun onClickOnEach(selectAble: RegionDto?) {
                        }
                    })
                    if (this.isShowing) return
                    this.show()
                }
            }
            5 -> {
                XToast.success(getString(R.string.already_delete))
                finishResult(null)
            }
        }
    }


    companion object {
        fun openActivity(mContext: BaseActivity<*, *>, addressDetails: AddressListDto?) {
            mContext.startForResult(
                bundleOf(Pair("addressDetails", addressDetails)),
                10001,
                EditAddressActivity::class.java
            )
        }
    }
}
